package com.shhic.hhplt.server.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import com.shhic.hhplt.server.service.ITestDbManageService;

/**
 * 初始化数据库工具
 * 如果没有数据库，则自动创建，
 * 这样，导出和备份数据变得很容易
 * @author 张文硕
 *
 */
public class InitDbUtil{
	ITestDbManageService tdmService;
	
	public void initDb(){
		if(tdmService.getTableCount() == 0){
			createNewTables();
		}
	}

	
	private void createNewTables() {
		String sql = getSql();
		tdmService.execSql(sql);
	}
	
	private String getSql(){
		File sqlFile = new File(InitDbUtil.class.getResource("/").getPath()+ "WEB-INF/db/hhplt.sql");
		StringBuilder sb = new StringBuilder();
		FileReader fr;
		try {
			fr = new FileReader(sqlFile);
	        BufferedReader br=new BufferedReader(fr);
	        while(true){
	        	String ln = br.readLine();
	        	if(ln!=null){
		            sb.append(ln);
	        	}else{
	        		break;
	        	}
	        }
	        
	        br.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
}
